<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: jerry.zzy
 * @Date: 2021-10-18 19:45:40
 * @LastEditors: jerry.zzy
 * @LastEditTime: 2021-10-18 20:07:07
-->
<!--
 * @Author: gaofang
 * @Date: 2020-11-03 09:16:59
 * @LastEditTime: 2021-09-17 20:54:35
 * @LastEditors: jerry.zzy
 * @Description: In User Settings Edit
 * @FilePath: \zhcc-zhqh\src\views\chukuguanli\ChuKuShenQing.vue
-->
<template>
  <div>
    <template>
      <a-card>
        <!-- 顶部 -->
        <a-form-model
          ref="ruleForm"
          :model="form"
          v-bind="layout"
          :rules="rules"
        >
          <a-row>
            <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
              <a-form-model-item ref="" label="申请单号" prop="">
                <a-input v-model="form.requisitionNo" disabled> </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
              <a-form-model-item
                label="申请日期"
                ref="applicationDate"
                prop="applicationDate"
              >
                <a-date-picker
                  v-model="form.applicationDate"
                  @change="onChange"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <!-- <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="所属单位">
            <a-select
              placeholder=""
              v-model="form.subordinate_text"
              @change="suoShuDanWeiTable"
            >
              <a-select-option
                v-for="(item, index) in storageList"
                :key="index"
                style="width: 100%"
                :value="item.depotNo + '|' + item.depotName + '|' + item.id"
                >{{ item.depotName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col> -->
            <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
              <a-form-model-item label="仓库名称">
                <a-select
                  placeholder=""
                  v-model="form.applicationDepot_text"
                  @change="setdataSourceDepartment"
                >
                  <a-select-option
                    v-for="(item, index) in storageList"
                    :key="index"
                    style="width: 100%"
                    :value="item.depotNo + '|' + item.depotName + '|' + item.id"
                    >{{ item.depotName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
              <a-form-model-item
                label="申请部门"
                ref="applicationDept_text"
                prop="applicationDept_text"
              >
                <a-tree-select
                  v-model="form.applicationDept_text"
                  show-search
                  style="width: 100%"
                  :tree-data="depTree"
                  allow-clear
                  @change="onChangeBumen"
                ></a-tree-select>
              </a-form-model-item>
            </a-col>
            <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
              <a-form-model-item
                label="申请人"
                ref="applicant_text"
                prop="applicant_text"
              >
                <a-input v-model="form.applicant_text" disabled> </a-input>
              </a-form-model-item>
            </a-col>
            <!-- <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
          <a-form-model-item ref="" label="收发类别" prop="">
            <a-select
              placeholder=""
              v-model="form.sendReceiveType_text"
              @change="shoufaleibieMethod"
            >
              <a-select-option
                v-for="(item, index) in shoufaleibieList"
                :key="index"
                :value="item.id + '|' + item.name"
                >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col> -->
            <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
              <a-form-model-item
                label="在建项目"
                ref="projectsUnderConstruction_text"
                prop="projectsUnderConstruction_text"
              >
                <a-select
                  v-model="form.projectsUnderConstruction_text"
                  @change="zaijianMethod"
                  style="width: 100%"
                  showSearch
                >
                  <a-select-option
                    v-for="(item, index) in zaijianList"
                    :key="index"
                    :value="
                      item.jobcode + '|' + item.jobname + '|' + item.pkJobbasfil
                    "
                  >
                    {{ item.jobname }}
                  </a-select-option>
                </a-select>
                <!-- <a-select
              placeholder=""
              v-model="form.projectsUnderConstruction_text"
              @change="zaijianMethod(form.projectsUnderConstruction_text)"
            >
              <a-select-option
                v-for="(item, index) in zaijianList"
                :key="index"
                :value="item.value + '|' + item.title"
                >{{ item.title }}
              </a-select-option>
            </a-select> -->
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <!-- <a-button @click="submitTemp">确定</a-button> -->
        <!-- 单据对应表格 -->
        <!-- <a-table
      :columns="columns"
      :data-source="dataSource"
      style="margin-top:10px"
      :rowKey="(col) => col.key"
      :pagination="false"
      :scroll="{ x: 2100 }"
    > -->

        <!-- <a-form-item
       
        :validate-status="getFildStatus(record.key).validateStatus"
        :help="getFildStatus(record.key).errorMsg"
         slot="applyNumber"
        slot-scope="text, record"
      >
        <a-input
        style="width: 100%"
          v-model="text.applyNumber"
          :min="0"
          @change="handleChangeapplyNumber(text.applyNumber, record.key)"
        />
      </a-form-item> -->

        <!-- 生成原单按钮组件 -->
        <planToApply
          @origin-data="getOriginData"
          @origin-data2="getOriginData2"
        ></planToApply>

        <a-table
          :columns="columns"
          :data-source="dataSource"
          style="margin-top: 10px"
          :pagination="false"
          :scroll="{ x: 2100 }"
        >
          <!-- <span slot="subordinate_text" slot-scope="text, record" label="所属单位">
        <a-select
          placeholder=""
          v-model="record.subordinate_text"
          @change="suoShuDanWeiTable2(record)"
          style="width: 100%"
        >
          <a-select-option
            v-for="(item, index) in storageList"
            :key="index"
            style="width: 100%"
            :value="item.depotNo + '|' + item.depotName + '|' + item.id"
            >{{ item.depotName }}
          </a-select-option>
        </a-select>
      </span> -->
          <span
            slot="applicationDepotCode_text"
            slot-scope="text, record"
            label="仓库编码"
          >
            <a-select
              v-model="record.applicationDepotCode_text"
              style="width: 100%"
              @change="setCangKuMingChengFunction(record)"
              showSearch
            >
              <a-select-option
                v-for="(item, index) in storageList"
                :key="index"
                style="width: 100%"
                :value="item.depotNo + '|' + item.depotName + '|' + item.id"
                >{{ item.depotNo }}{{ item.depotName }}
              </a-select-option>
            </a-select>
          </span>
          <span slot="inventoryNane" slot-scope="text, record" label="存货名称">
            <a-select
              v-model="record.inventoryNane"
              style="width: 100%"
              :default-active-first-option="false"
              :show-arrow="false"
              :filter-option="false"
              :not-found-content="null"
              @search="handleSearch"
              @change="setCunHuoBianMaFunction(record)"
              showSearch
            >
              <a-select-option
                v-for="(item, index) in goodsList"
                :key="index"
                :value="
                  item.inventoryId +
                  '|' +
                  item.inventoryNo +
                  '|' +
                  item.inventoryNane +
                  '|' +
                  item.specificationsModel +
                  '|' +
                  item.unit
                "
              >
                {{ item.inventoryNo }} {{ item.inventoryNane }}
                {{ item.specificationsModel }}
              </a-select-option>
            </a-select>
          </span>

          <span slot="applyNumber" slot-scope="text, record" label="申请数量">
            <a-input-number
              v-model="record.applyNumber"
              :min="0"
              :precision="3"
            />
          </span>
          <!-- 实发数量 -->
          <!-- <span slot="actualQuantity" slot-scope="text, record" label="实发数量">
        <a-input-number v-model="record.actualQuantity" :min="0" />
      </span> -->
          <!-- 操作 -->
          <span slot="action" slot-scope="text, record">
            <a-popconfirm
              title="确定取消?"
              @confirm="() => cancle(record.key)"
              okText="确定"
              cancelText="取消"
            >
              <a> 取消</a>
            </a-popconfirm>
          </span>
        </a-table>
        <a-button
          style="width: 100%; margin-top: 16px; margin-bottom: 8px"
          type="dashed"
          icon="plus"
          @click="newMember"
          >添加</a-button
        >

        <a-descriptions
          bordered
          :column="{ xxl: 3, xl: 3, lg: 3, md: 3, sm: 1, xs: 1 }"
          style="text-align: right"
        >
          <a-descriptions-item label="部门负责人意见" :span="3">
            <div style="height: 60px; width: 800px">
              <a-textarea
                style="background-color: white; color: black; border: 0"
                :auto-size="{ minRows: 4 }"
                placeholder="填写部门负责人意见"
                disabled
              />
              <a-row>
                <a-col :span="9"></a-col>
                <a-col :span="9">签名：</a-col>
                <a-col :span="6">日期：</a-col>
              </a-row>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="仓库管理员意见" :span="3">
            <div style="height: 60px; width: 800px">
              <a-textarea
                style="background-color: white; color: black; border: 0"
                :auto-size="{ minRows: 4 }"
                placeholder="填写仓库管理员意见"
                disabled
              />
              <a-row>
                <a-col :span="9"></a-col>
                <a-col :span="9">签名：</a-col>
                <a-col :span="6">日期：</a-col>
              </a-row>
            </div>
          </a-descriptions-item>
        </a-descriptions>
        <workflow
          :duty_name="duty_name"
          @submit-assignee="Submit"
          @reset-form="resetForm"
          ref="workflow"
        ></workflow>
      </a-card>
    </template>
  </div>
</template>


<script>
// 加载工作流组件
import workflow from "@/components/common/workFlow";

import moment from "moment";
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口

import { JiJianChuKuShenQingHttp } from "@/services/modules/ChuKuGuanLi/JJianChuKu/JiJianChuKuShenQing";
const $http = new JiJianChuKuShenQingHttp(); // 基建出库申请

// import { ZiDianBiaoHttp } from "@/services/modules/ZiDianBiao";
// const zidianbiao = new ZiDianBiaoHttp(); // 字典表
import { JiJianChuKuHttp } from "@/services/modules/ChuKuGuanLi/JJianChuKu/JiJianChuKu";
const JiJianChuKu = new JiJianChuKuHttp(); // 基建出库

import planToApply from "../planToApply.vue"; //

// 物品信息表格
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },
  // {
  //   title: "所属单位",
  //   key: "subordinate_text",
  //   dataIndex: "subordinate_text",
  //   width: 230,
  //   align: "center",
  //   scopedSlots: { customRender: "subordinate_text" },
  // },
  {
    //! 这里传编码
    title: "仓库编码",
    key: "applicationDepotCode_text",
    dataIndex: "applicationDepotCode_text",
    width: 280,

    align: "center",
    scopedSlots: { customRender: "applicationDepotCode_text" },
  },
  {
    //! 传name
    title: "仓库名称",
    key: "applicationDepot_text",
    dataIndex: "applicationDepot_text",
    align: "center",
  },
  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",

    align: "center",
  },
  {
    title: "存货名称",
    dataIndex: "inventoryNane",
    key: "inventoryNane",
    width: 400,
    align: "center",
    scopedSlots: { customRender: "inventoryNane" },
  },
  {
    title: "规格型号",
    dataIndex: "standardModel",
    key: "standardModel",
    align: "center",
  },
  {
    title: "单位",
    key: "unit",
    dataIndex: "unit",
    align: "center",
  },

  {
    title: "现存数量",
    key: "balance",
    dataIndex: "balance",
    align: "center",
  },
  {
    title: "申请数量",
    dataIndex: "applyNumber",
    key: "applyNumber",
    align: "center",
    scopedSlots: { customRender: "applyNumber" },
  },
  // {
  //   title: "实发数量",
  //   dataIndex: "actualQuantity",
  //   key: "actualQuantity",
  //   align: "center",
  //   // scopedSlots: { customRender: "actualQuantity" },
  // },

  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    scopedSlots: { customRender: "action" },
  },
];
//验证
function validatePrimeNumber(value) {
  if (value !== "") {
    return {
      validateStatus: "success",
      errorMsg: "",
    };
  }
  return {
    validateStatus: "error",
    errorMsg: "数量不能为空",
  };
}
// 备货通知中的物品信息
export default {
  data() {
    return {
      //部门中的id和title一起存储
      buMenList: [],
      goodsList: [],
      data: [],

      // shoufaleibieList: [], //收发类别下拉列表
      zaijianList: [], //在建项目列表
      duty_name: "基建流程", // 目的是从已办任务中查询，判断任务是否多次申请

      depTree: [], //申请部门列表
      //存货编码、id/inventoryName/inventoryNo/specificationsModel/unit
      // CunHuoBianMaList: [],
      //查询表单
      form: {
        requisitionNo: "", // 申请单号
        applicationDate: moment().format("YYYY-MM-DD"), // 单据日期
        // subordinate_text: "", //! 所属单位(传name),和申请仓库一个接口,接口暂时没有，先不用传
        applicationDepot: "", // 仓库名称id
        depotId: "", // 仓库名称id-以后源单的时候使用
        applicationDepot_text: "", // 仓库名称name
        applicationDept: "", // 申请部门id
        applicationDept_text: "", // 申请部门name
        applicant: "", // 申请人id
        applicant_text: "", // 申请人name
        // sendReceiveType: "", // 收发类别id
        // sendReceiveType_text: "", // 收发类别name
        projectsUnderConstruction_text: "", // 在建项目  名字
        projectsUnderConstruction: "", // 在建项目  id
      },

      //仓库名称下拉框、所属单位下拉框
      storageList: [],

      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      visible: false,

      columns,
      dataSource: [],
      selectedRowKeys: [],

      // 校验规则
      rules: {
        applicationDate: [
          {
            required: true,
            message: "申请日期不能为空！",
            trigger: "change",
          },
        ],
        applicationDept_text: [
          {
            required: true,
            message: "申请部门不能为空！",
            trigger: "change",
          },
        ],
        applicant_text: [
          {
            required: true,
            message: "申请人不能为空！",
            trigger: "change",
          },
        ],
        projectsUnderConstruction_text: [
          {
            required: true,
            message: "在建项目不能为空！",
            trigger: "change",
          },
        ],
      },

      applyNumberData: [], //表格验证测试-申请数量
    };
  },
  components: {
    workflow,
    planToApply,
  },
  // 生命周期函数
  mounted() {
    this.judgeDocument(); //判断单据号是否为空
    this.getZaiJianList(); //在建项目列表
    //设置表格迷人填充5行
    this.setDatasource();
    //申请部门
    this.getDeparmentTree();
    // 获取仓库
    this.getApplyStorage();
    //获取人员信息
    // this.getUserIdByRoleName();

    this.getUserByToken();
    // this.shoufaleibieListmethod();
    // this.getInventoryInformation(); //获取存货编码、存货名称、规格型号、单位下拉框
    // 传递过去任务名称，获取流程数组
    this.sendDutyName();
    // 获取单号
    this.getApplyOrder();
    //在建项目
    // this.zaijianListMethod();
  },
  methods: {
    /**
      //todo @description: 2.0功能
      * @description: ...
      * @return
      */
    getOriginData(data) {
      console.log(data);
    },
    getOriginData2(data) {
      console.log("传入的存货信息:::::", data);

      this.dataSource = data;
      data.forEach((item) => {
        item.inventoryNane = item.inventoryName;
        item.standardModel = item.specifications;
      });
    },
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.form.requisitionNo === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    //-------------------------表格验证大礼包:开始---------------------------
    getFildStatus(id) {
      const data = this.applyNumberData.filter((item) => id === item.id)[0];
      if (data) {
        return data;
      } else {
        return {
          errorMsg: "",
          validateStatus: "success",
        };
      }
    },
    handleChangeapplyNumber(value, id) {
      console.log("打印数据value", value);
      console.log("打印数据id", id);
      const newData = [...this.dataSource];
      const target = newData.filter((item) => item.id === id)[0];
      if (target) {
        const { errorMsg, validateStatus } = validatePrimeNumber(value);
        let flag = true;
        this.applyNumberData.forEach((val) => {
          if (val.id === id) {
            flag = false;
            (val.errorMsg = errorMsg), (val.validateStatus = validateStatus);
          }
        });

        if (flag) {
          this.applyNumberData.push({
            id,
            errorMsg,
            validateStatus,
          });
        }
        target.applyNumber = value;
        this.dataSource = newData;
      }
    },

    //提交按钮-触发验证
    submitTemp() {
      this.dataSource.forEach((element) => {
        if (this.form.requisitionNo !== "") {
          this.handleChangeapplyNumber(element.applyNumber, element.key);
        } else {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }

        console.log("进入");
      });
    },
    //-------------------------表格验证大礼包:结束---------------------------
    async handleSearch(value) {
      var goodsList_invname = [];
      var goodsList_invspec = [];
      if (value.match(/^[ ]*$/)) {
        console.log("字符串为空或全空格");
      } else {
        this.goodsList = [];
        console.log("value", value);
        let query = "?name=" + value;
        console.log("query", query);
        if (value == "" || value == null) {
          this.goodsList = [];
        } else {
          await comHttp
            .getgetSearchInventoryInformationFile(query)
            .then((res) => {
              console.log("结果为", res);
              // this.goodsList = res.result;
              for (let i = 0; i < res.result.length; i++) {
                if (
                  res.result[i].specificationsModel == "null" ||
                  res.result[i].specificationsModel == null
                ) {
                  res.result[i].specificationsModel = "";
                }
                if (
                  res.result[i].unit == "null" ||
                  res.result[i].unit == null
                ) {
                  res.result[i].unit = "";
                }
                let data = {
                  inventoryId: res.result[i].pkInvbasdoc, // 存货 id
                  inventoryNo: res.result[i].invcode, //存货编码
                  inventoryNane: res.result[i].invname, //存货名称
                  specificationsModel: res.result[i].invspec, //规格型号
                  unit: res.result[i].measname, //单位
                };
                goodsList_invname.push(data);
              }
            });

          let queryInventoryBySpec = "?invspec=" + value;
          //规格型号模糊查询
          await comHttp
            .getqueryInventoryBySpec(queryInventoryBySpec)
            .then((res) => {
              console.log("结果规格型号模糊查询", res);

              goodsList_invspec = res.result.list.map((item) => {
                return {
                  inventoryId: item.pkInvbasdoc,
                  inventoryNo: item.invcode,
                  inventoryNane: item.invname,
                  specificationsModel: item.invspec,
                  unit: item.measname,
                };
              });
            });
          //todo 合并去重函数
          await this.mergeArray(goodsList_invname, goodsList_invspec);
        }
      }
    },
    //todo 合并去重函数
    mergeArray(arr1, arr2) {
      let arrs = [...arr1, ...arr2];

      //根据inventoryId去重
      let map = new Map();
      for (let item of arrs) {
        if (!map.has(item.inventoryId)) {
          map.set(item.inventoryId, item);
        }
      }
      this.goodsList = [...map.values()];
    },
    //获取在建项目列表
    getZaiJianList() {
      JiJianChuKu.getZaiJian().then((res) => {
        console.log("在建项目", res);
        this.zaijianList = res.result;
      });
    },
    //在建项目触发函数
    zaijianMethod(value) {
      console.log("在建项目触发函数value", value);
      let array = value.split("|");
      console.log("array", array);
      console.log("parseInt(array[2])", parseInt(array[2]));
      console.log("(array[2])", array[2]);

      console.log("类型", typeof array[2]);
      this.form.projectsUnderConstruction = array[2];
      this.form.projectsUnderConstruction_text = array[1];
      console.log("在建项目触发函数this.form", this.form);
    },
    // 获取单号
    getApplyOrder() {
      comHttp.getOrder("?string=" + "JJSQ-").then((res) => {
        this.form.requisitionNo = res.message;
      });
    },
    //收发类别列表
    // shoufaleibieListmethod(queryPath = "") {
    //   console.log("hfougdiuy");
    //   comHttp.getReceiveSendTypeList(queryPath).then((res) => {
    //     console.log("收发类别列表", res);
    //     this.shoufaleibieList = res.result.records;
    //   });
    // },
    //收发类别触发函数
    // shoufaleibieMethod(value) {
    //   console.log("收发类别触发函数value", value);
    //   let array = value.split("|");
    //   console.log("array", array);
    //   // 表格自动填充所属单位
    //   this.form.sendReceiveType = array[0]; //收发类别id
    //   this.form.sendReceiveType_text = array[1]; //收发类别name
    // },

    //  根据TOKEN获取用户的部分信息
    getUserByToken(queryPath = "") {
      // console.log(" this.$store.state.user.info.username", this.$store.state);
      comHttp.getUserByToken(queryPath).then((res) => {
        console.log("我i进来了", res);
        this.form.applicant_text = res.result.sysUsername;
        this.form.applicant = res.result.sysUserId;
        // this.getuserdepartments();//根据当前登陆人获取部门,自动填充申请部门
        this.getDeptByUserId(this.form.applicant).then((res) => {
          this.form.applicationDept_text = res.accountingDept_dictText;
          this.form.applicationDept = res.accountingDept;
          console.log("this.form.applicationDepart", this.form.applicationDept);
        });
      });
    },
    //根据当前登陆人获取部门
    // getuserdepartments(){
    //   this.form.applicationDept=this.$store.state.user.departments[0].id;
    //   this.form.applicationDept_text=this.$store.state.user.departments[0].departName;
    // },
    // 根据用户获取该用户的部门
    getDeptByUserId(userId) {
      let queryPath = "?userId=" + userId;
      return new Promise((resolve) => {
        comHttp.getDeptByUserId(queryPath).then((res) => {
          console.log("res++++userId+", res);
          let accountingDeptID = res.result.object;
          resolve(accountingDeptID);
          // this.getUserByDeptId(accountingDeptID);
        });
      });
    },
    // 获取部门列表
    getDeparmentTree() {
      // console.log("获取部门列表hanshu===");
      comHttp.getDepartmentTreeNew().then((res) => {
        if (res.success) {
          // console.log("获取部门树", res);
          this.depTree = res.result;

          this.getYongYou(this.depTree);
          // console.log("this.depTree", this.depTree);
        }
      });
    },
    //将用友中采购部门的格式转换成Tree识别的格式
    getYongYou(tree) {
      tree.forEach((element) => {
        element["title"] = element.deptcode + " " + element.deptname;
        element["value"] = element.pkDeptdoc + "|" + element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.getYongYou(element.children);
        }
      });
    },
    // // 获取部门列表
    // getDeparmentTree() {
    //   console.log("获取部门列表hanshu===");
    //   comHttp.getDepartmentList().then((res) => {
    //     if (res.success) {
    //       let resetRes = res.result;
    //       this.resetDepartmentTree(resetRes);
    //       this.depTree = resetRes;
    //     }
    //   });
    // },
    // // 部门字典表中每一项vlaue 变成 title 为了方便搜索
    // resetDepartmentTree(dep) {
    //   dep.forEach((item) => {
    //     item.value = item.title;
    //     let temp = {
    //       value: item.value,
    //       id: item.id,
    //     };
    //     this.buMenList.push(temp);
    //     if (item.children) {
    //       this.resetDepartmentTree(item.children);
    //     }
    //   });
    // },
    //根据提交部门的title，找到对应value,并给部门id赋值
    onChangeBumen(a) {
      console.log("a", a);
      let array = a.split("|");
      this.form.applicationDept = array[0];
      this.form.applicationDept_text = array[1];
    },
    // onChangeBumen(value, b, c, d) {
    //   console.log("value", value);
    //   console.log("b", b);
    //   console.log("c", c);
    //   console.log("d", d);
    //   console.log("this.form", this.form);
    //   // this.form.bumen = [];
    //   // this.form.bumen = value;
    //   for (let i = 0; i < this.buMenList.length; i++) {
    //     if (value == this.buMenList[i].value) {
    //       // this.form.draftDepartment = this.buMenList[i].id;

    //       this.form.applicationDept = this.buMenList[i].id; //申请部门id
    //       this.form.applicationDept_text = this.buMenList[i].value; //申请部门名称

    //       break;
    //     }
    //   }
    //   console.log("1111111111", this.form);
    //   // comHttp.getdepartmentlistTree().then((res) => {
    //   //   console.log("res.result.children", res.result[0].children);
    //   //   let array = res.result[0].children;
    //   //   console.log("array!", array);
    //   //   for (let i = 0; i < array.length; i++) {
    //   //     console.log("进入1");
    //   //     if (array[i].title == value) {
    //   //       this.form.applicationDept = array[i].key; //申请部门id
    //   //       this.form.applicationDept_text = array[i].title; //申请部门名称
    //   //       console.log("这是最终的form", this.form);
    //   //     }
    //   //   }
    //   // });
    // },
    //获取存货编码
    getInventoryInformation() {
      comHttp.getInventoryInformation().then((res) => {
        console.log("getInventoryInformation获取存货编码", res);
        // this.CunHuoBianMaList = res.result; //存的是inventoryNo
        for (let i = 1; i < res.result.length; i++) {
          // let data = {
          //   inventoryNo: res.result[i].id,
          //   inventoryNoTemp: res.result[i].inventoryNo,
          //   materialName: res.result[i].inventoryName,
          //   materialStandard: res.result[i].specificationsModel,
          //   company: res.result[i].unit,
          // };
          let data = {
            inventoryNo: res.result[i].inventoryNo,
            inventoryNane: res.result[i].inventoryName,
            standardModel: res.result[i].specificationsModel,
            unit: res.result[i].unit,
          };
          this.goodsList.push(data);
          console.log("获取存货编码内部循环", this.goodsList);
        }
        console.log("获取存货编码", this.goodsList);
      });
    },
    //存货编码自动填充：存货名称、规格型号、单位
    setCunHuoBianMaFunction(record) {
      let key = record.key;
      console.log("record", record);
      console.log("key", record.key);
      console.log("inventoryNo", record.inventoryNo);

      let array = record.inventoryNane.split("|");
      console.log("array", array);
      if (
        array[2] == null ||
        array[2] == "null" ||
        array[2] == "undefined" ||
        array[2] == undefined
      ) {
        array[2] = "";
      }
      if (
        array[3] == null ||
        array[3] == "null" ||
        array[3] == "undefined" ||
        array[3] == undefined
      ) {
        array[3] = "";
      }
      this.dataSource[key - 1].inventoryId = array[0];
      this.dataSource[key - 1].inventoryNo = array[1];
      this.dataSource[key - 1].inventoryNane = array[2];
      this.dataSource[key - 1].standardModel = array[3];
      this.dataSource[key - 1].unit = array[4];
    },
    //选择仓库编码，自动填充仓库名称
    setCangKuMingChengFunction(record) {
      console.log("选择仓库编码，自动填充仓库名称", record);
      let array = record.applicationDepotCode_text.split("|");
      // let key = record.key;
      console.log("array", array);
      this.dataSource[record.key - 1].applicationDepotCode_text = array[0]; //仓库编码-传编码
      this.dataSource[record.key - 1].applicationDepot_text = array[1]; //仓库名称-传name
      this.dataSource[record.key - 1].applicationDepot = array[2]; //仓库名称-传id
      this.dataSource[record.key - 1].depotId = array[2]; //仓库名称-传id
      this.getBalanceTemp(record); //获取现存数量
    },
    //获取现存数量
    getBalanceTemp(record) {
      console.log("record", record);
      let data = {
        batchNumber: record.batchNumber,
        depotId: record.depotId,
        inventoryId: record.inventoryId,
        position: record.position,
      };

      let temp = 0;
      JiJianChuKu.getTotalGoods(data).then((res) => {
        console.log("货物返回值res", res);
        temp = res.result.balance;
        // record.balance = temp; //给本条数据赋值
        this.$set(record, "balance", temp);
        console.log("record22222222222222222", record);

        return Promise.resolve(temp);
      });
    },

    // 获取仓库
    getApplyStorage() {
      this.storageList = [];
      // 获取仓库名称
      comHttp.getStorageName().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            id: res.result[i].pkStordoc, //id
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode, //仓库编码
          };
          this.storageList.push(data);
        }
        console.log("this.storageList", this.storageList);
      });
    },
    // // 获取人员信息
    // getUserIdByRoleName() {
    //   const roleName = "出库申请人员";
    //   let queryPath = "?roleName=" + roleName;
    //   comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
    //     // console.log(res);
    //     for (let i = 0; i < res.result.length; i++) {
    //       let data = {
    //         userName: res.result[i].userName,
    //         userId: res.result[i].userId,
    //         workNo: res.result[i].workNo,
    //       };
    //       this.ApplyPersonList.push(data);
    //     }
    //     console.log(this.ApplyPersonList);
    //   });
    // },

    //点击仓库名称-仓库编码、仓库名称自动填入表内
    setdataSourceDepartment(value, option) {
      console.log("所属单位-自动填充表格内value", value);
      console.log("所属单位-自动填充表格内option", option);
      let array = value.split("|");
      console.log("array", array);
      this.form.applicationDepot_text = array[1]; //所属单位name
      // 表格自动填充所属单位
      for (let i = 0; i < this.dataSource.length; i++) {
        this.dataSource[i].applicationDepotCode_text = array[0];
        this.dataSource[i].applicationDepot_text = array[1];
        this.dataSource[i].applicationDept = array[2]; //申请部门id
        this.dataSource[i].depotId = array[2]; //申请部门id
      }
    },
    //所属单位-自动填充表格内
    // suoShuDanWeiTable(value, option) {
    //   console.log("所属单位-自动填充表格内value", value);
    //   console.log("所属单位-自动填充表格内option", option);
    //   let array = value.split("|");
    //   console.log("array", array);
    //   this.form.subordinate_text = array[1]; //所属单位name
    //   // let key = option.key;
    //   // 表格自动填充所属单位
    //   for (let i = 0; i < this.dataSource.length; i++) {
    //     // this.dataSource[i].subordinate_text = array[0];
    //     this.dataSource[i].subordinate_text = array[1];
    //     this.dataSource[i].storageUnit = array[2];
    //     // this.dataSource[i].StorageUnitId = key;
    //   }
    // },
    //插槽-所属单位出发函数
    // suoShuDanWeiTable2(record) {
    //   console.log("所属单位-自动填充表格内record", record);
    //   let key = record.key - 1;
    //   let array = record.subordinate_text.split("|");
    //   this.dataSource[key].subordinate_text = array[1];
    //   this.dataSource[key].storageUnit = array[2];
    // },

    // 表单重置
    resetForm() {
      this.$refs.workflow.ResetASSIGNEE();
      this.form = {
        requisitionNo: "", // 申请单号
        applicationDate: moment().format("YYYY-MM-DD"), // 单据日期
        // subordinate_text: "", //! 所属单位(传name),和申请仓库一个接口,接口暂时没有，先不用传
        applicationDepot: "", // 仓库名称id
        depotId: "", // 仓库名称id-以后源单的时候使用
        applicationDepot_text: "", // 仓库名称name
        applicationDept: "", // 申请部门id
        applicationDept_text: "", // 申请部门name
        applicant: "", // 申请人id
        applicant_text: "", // 申请人name
        // sendReceiveType: "", // 收发类别id
        // sendReceiveType_text: "", // 收发类别name
        projectsUnderConstruction_text: "", // 在建项目  名字
        projectsUnderConstruction: "", // 在建项目  id
      };
      this.dataSource = [];
      this.setDatasource();
      // 获取单号
      this.getApplyOrder();
      this.getUserByToken();
    },
    // 传递过去任务名称，获取流程数组
    sendDutyName() {
      this.$refs.workflow.getProcessName();
    },
    //  提交函数
    Submit(queryPath) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log("Submit(queryPath)：ASSIGNEE_", queryPath); //返回下一步办理人数组
          console.log("submit的form", this.form);
          // let subordinate_textFlag = true; //所属单位
          let applicationDepotCode_textFlag = true; //仓库编码
          let inventoryNoFlag = true; //存货编码
          let applyNumberFlag = true; //申请数量

          this.dataSource.forEach((element) => {
            // if (element.subordinate_text == "") {
            //   subordinate_textFlag = false;
            // }
            if (element.applicationDepotCode_text == "") {
              applicationDepotCode_textFlag = false;
            }
            if (element.inventoryNo == "") {
              inventoryNoFlag = false;
            }
            if (element.applyNumber == "") {
              applyNumberFlag = false;
            }
          });
          if (
            // subordinate_textFlag &&
            applicationDepotCode_textFlag &&
            inventoryNoFlag &&
            applyNumberFlag
          ) {
            // let a=parseInt(this.form.draftDepartment);
            // console.log("this.form.draftDepartment",this.form.draftDepartment);
            // console.log("aaaaaaaaaaaaaaa",a);
            console.log(
              " &projectsUnderConstruction=",
              this.form.projectsUnderConstruction
            );

            let queryPathTemp =
              queryPath +
              "&requisitionNo=" + //申请单号
              this.form.requisitionNo +
              "&applicationDate=" + //申请日期
              this.form.applicationDate +
              "&applicationDept=" + //申请部门id
              this.form.applicationDept +
              "&applicationDept_text=" + //申请部门name
              this.form.applicationDept_text +
              "&applicant=" + //申请人id
              this.form.applicant +
              "&applicant_text=" + //申请人name
              this.form.applicant_text +
              "&projectsUnderConstruction=" + //在建项目id
              this.form.projectsUnderConstruction +
              "&projectsUnderConstruction_text=" + //在建项目name
              this.form.projectsUnderConstruction_text;
            // "&sendReceiveType=" + //收发类型-传ID
            // this.form.sendReceiveType +
            // "&sendReceiveType_text=" + //收发类型-传name
            // this.form.sendReceiveType_text +

            console.log("this.datasource", this.dataSource);
            console.log("queryPathTemp", queryPathTemp);

            let warehouseInfrastructureDeliveryContentEntityList = [];
            for (let i = 0; i < this.dataSource.length; i++) {
              console.log("进入1111111111！");
              let data = {
                // applicationDepot: "18"
                // applicationDepotCode_text: "010105"
                // applicationDepot_text: "双泉菌种库"
                // applyNumber: 10
                // depotId: "18"
                // inventoryId: "209145"
                // inventoryNane: "香菇菌棒纸箱（海王红）"
                // inventoryNo: "0103015"
                // key: 1
                // standardModel: "415*385*290"
                // storageUnit: 19
                // subordinate_text: "双泉菌棒库"
                // unit: "个"

                // applicationDept: this.form.applicationDepot,
                depotId: this.dataSource[i].depotId, //申请仓库id
                storageUnit: this.dataSource[i].storageUnit, //所属单位id
                // subordinate_text: this.dataSource[i].subordinate_text, //所属单位-传name
                applicationDepotCode_text:
                  this.dataSource[i].applicationDepotCode_text, //仓库编码-传编码
                // applicationDepot_text: this.dataSource[i].applicationDepot_text[
                //   i
                // ], //仓库名称-传name
                applicationDepot_text: this.dataSource[i].applicationDepot_text, //仓库名称-传name
                inventoryNo: this.dataSource[i].inventoryNo, //存货编码
                inventoryNane: this.dataSource[i].inventoryNane, //存货名称
                standardModel: this.dataSource[i].standardModel, //规格型号
                unit: this.dataSource[i].unit, //单位
                applyNumber: Number(this.dataSource[i].applyNumber), //申请数量
                // actualQuantity: parseInt(this.dataSource[i].actualQuantity), //实发数量
              };
              console.log("进入2222222222");

              warehouseInfrastructureDeliveryContentEntityList.push(data);
              console.log("进入3333333333");
            }
            console.log("datasource循环外", this.dataSource);
            console.log(
              "this.datasource循环外",
              warehouseInfrastructureDeliveryContentEntityList
            );
            console.log("提交的数据上半部分queryPathTemp", queryPathTemp);
            console.log(
              "提交的数据下半部分warehouseInfrastructureDeliveryContentEntityList",
              warehouseInfrastructureDeliveryContentEntityList
            );
            $http
              .warehouseinfrastructuredelivery(
                queryPathTemp,
                warehouseInfrastructureDeliveryContentEntityList
              )
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success("提交成功");
                  this.resetForm(); // 重置表单
                } else {
                  this.$message.error("提交失败");
                }
              });
          } else {
            this.$message.error("请把表中信息填写完整");
          }
        } else {
          this.$message.error("请把头部信息填写完整");

          return false;
        }
      });
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource];
      const target = dataSource.find((item) => item.key === key);
      if (target) {
        target[dataIndex] = value;
        this.dataSource = dataSource;
      }
    },
    onDelete(key) {
      if (this.dataSource.length > 1) {
        const dataSource = [...this.dataSource];
        dataSource.shift(key, 1);
        this.dataSource = dataSource;
        // this.dataSource = dataSource.filter((item) => item.key !== key);
        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },

    // 默认设置五行，让用户方便添加
    setDatasource() {
      let size = 1;
      for (let i = 0; i < size; i++) {
        let data = {
          key: i + 1,
          // isNew: true,
          // subordinate_text: "", //所属单位
          applicationDepotCode_text: "", //仓库编码
          applicationDepot_text: "", //仓库名称
          inventoryNo: "", //存货编码
          inventoryNane: "", //存货名称
          standardModel: "", //规格型号
          unit: "", //单位
          applyNumber: "", //申请数量
          actualQuantity: "", //实发数量
        };
        this.dataSource.push(data);
      }
      // console.log("默认加载的数据::::",this.DataSource)
    },
    //申请日期触发函数
    onChange(date, dateString) {
      console.log("date", date);
      console.log("dateString", dateString);
      this.form.applicationDate = dateString;
    },
    showModal() {
      this.visible = true;
    },
    handleOk() {
      this.ModalText = "The modal will be closed after two seconds";
      this.confirmLoading = true;
      setTimeout(() => {
        this.visible = false;
        this.confirmLoading = false;
      }, 2000);
    },
    handleCancel() {
      console.log("Clicked cancel button");
      this.visible = false;
    },
    // 表格添加新的一条记录
    newMember() {
      this.dataSource.push({
        key: this.dataSource.length + 1,
        // isNew: true,
        suoshudanwei: "", //所属单位
        applicationDepot: "", //仓库编码
        applicationDepotName: "", //仓库名称
        inventoryNo: "", //存货编码
        inventoryNane: "", //存货名称
        standardModel: "", //规格型号
        unit: "", //单位
        balance: "", //现存数量
        applyNumber: "", //申请数量
        actualQuantity: "", //实发数量
      });
    },
    // 表格取消一行
    cancle(key) {
      // console.log(key);
      if (this.dataSource.length > 1) {
        this.dataSource.splice(key - 1, 1);
        this.resetdataSource();
        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },
    //对表格中数据得序号重新命名
    resetdataSource() {
      for (let i = 0; i < this.dataSource.length; i++) {
        this.dataSource[i].key = i + 1;
      }
    },

    // 表格选择事件
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
  },
};
</script>
<style></style>
